import { createStore } from "vuex";
import request from "../components/request";

export default createStore({
  state() {
    return {
      user: null,
    };
  },
  getters: {
    avatar(state) {
      // 使用可选链运算符避免错误
      return state.user?.avatar
        ? `/avatars/${state.user.avatar}`
        : `/multi-avatar/${
            state.user?.nickname ? state.user.nickname : "default"
          }.svg`;
    },
  },
  mutations: {
    login(state, user) {
      state.user = user;
    },
    logout(state) {
      state.user = null;
    },
  },
  actions: {
    async getUserInfo({ state, commit }) {
      if (state.user != null) return;
      try {
        const { data } = await request("/user/info");
        if (data.success) {
          commit("login", data.user);
        }
      } catch {}
    },
  },
});
